import React, { Component } from 'react';
import { Button, Modal, Form, Alert, Divider, Badge, PageHeader, Tabs } from 'antd';
import '@/assets/css/settings';
import * as ProductionOrderService from '../../../axios/ProductionOrder'
import * as ProcessQualityControlService from '../../../axios/ProcessQualityControl'
import * as APIService from '../../../axios/api_px'
import { BasicLayoutSearch } from '../../../components/BasicLayout';
import { BasicPagination, isInvalidObject, TableCustomize, openSuccessModal, openModalMessage, compareString } from '../../../components/TableCustomize'
import { checkResultList } from '../../../utils/global';
import SearchForm from './SearchForm';
import SelfCheckingSearchForm from './SelfCheckingSearchForm';
import SelfChecking from './SelfChecking';
import AddForm3 from './AddForm3';
import { withRouter } from 'react-router';
import { withPermission } from '../../../components/withpermission'
const XZButton = withPermission(Button, 'edit')
const DownLoadButton = withPermission(Button, 'download')

const { TabPane } = Tabs;
class ProcessQualityControl extends Component {
  state = {
    imgList: [],
    data: {},
    dataSource: [],
    departmentList: [],
    procedureData: [],
    advanced: false,
    searchItem: {
      department: localStorage.getItem('workShop')
    },
    selfSearchItem: {},
    activeKey: '0',
    pageSize: 10,
    pageNum: 1,
    total: 0,
    columns: [
      {
        title: '序号',
        dataIndex: 'dataIndex',
        align: 'center',
        width: 50,
        render: (text, record, index) => <span>{(this.state.pageNum - 1) * (this.state.pageSize) + index + 1}</span>
      },
      {
        title: '批号',
        dataIndex: 'batchNo',
        width: 100,
        sorter: (a, b) => compareString(a.batchNo, b.batchNo)
      },
      {
        title: '过程记录表',
        width: 250,
        dataIndex: 'formName',
        sorter: (a, b) => compareString(a.formName, b.formName)
      },
      // {
      //   title: '表单编码',
      //   width: 100,
      //   dataIndex: 'formCoding',
      //   sorter: (a, b) => compareString(a.formCoding, b.formCoding)
      // },
      {
        title: '装配员',
        width: 100,
        dataIndex: 'assemName',
        sorter: (a, b) => compareString(a.assemName, b.assemName)
      },
      {
        title: '创建时间',
        width: 150,
        dataIndex: 'assemTime',
        sorter: (a, b) => compareString(a.assemTime, b.assemTime)
      },
      {
        title: '组长',
        width: 100,
        dataIndex: 'assemLeaderName',
        sorter: (a, b) => compareString(a.assemLeaderName, b.assemLeaderName)
      },
      {
        title: '创建时间',
        width: 150,
        dataIndex: 'assemLeaderTime',
        sorter: (a, b) => compareString(a.assemLeaderTime, b.assemLeaderTime),
      },
      {
        title: '质检员',
        width: 100,
        dataIndex: 'qualityName',
        sorter: (a, b) => compareString(a.qualityName, b.qualityName)
      },
      {
        title: '创建时间',
        width: 150,
        dataIndex: 'qualityTime',
        sorter: (a, b) => compareString(a.qualityTime, b.qualityTime)
      },
      {
        title: '结果',
        width: 100,
        dataIndex: 'checkResult',
        sorter: (a, b) => compareString(a.checkResult, b.checkResult),
        render: (text, record, index) => {
          let a = checkResultList.find(item => item.id == text)
          return a.id == '0' ? <Badge color='#1890ff' text={<span style={{ color: '#1890ff' }}>{a.value}</span>} />
            : a.id == '1' ? <Badge status="success" text={<span style={{ color: '#1e8e3e' }}>{a.value}</span>} />
              : a.id == '2' ? <Badge status="error" text={<span style={{ color: '#f00' }}>{a.value}</span>} />
                : a.value
        }
      },
      {
        title: '操作',
        width: 100,
        dataIndex: 'opts',
        render: (text, record) => <>
          <a onClick={() => this.edit(record)}>详情/编辑</a>
        </>
      },
      { dataIndex: '', }
    ],
    selectedRows: [],
    selectedRowKeys: [],
    btnLoading: false,
    visiable_AddForm3: false,

  };
  componentDidMount() {
    this.getList()
    console.log(this.props.location, 'this.props.location');
    if (this.props.location?.data) {
      this.setState({
        searchItem: this.props.location.data.searchItem ? this.props.location.data.searchItem : { department: localStorage.getItem('workShop') },
        selfSearchItem: this.props.location.data.selfSearchItem ? this.props.location.data.selfSearchItem : {},
        activeKey: this.props.location.data.activeKey ? this.props.location.data.activeKey : '0'
      }, this.handleSearch)
    } else {
      this.handleSearch()
    }
  }
  componentWillUnmount() {
    this.setState = () => {
      return;
    };
  }
  // 过程记录生成
  init = () => {
    this.setState({ loading: true })
    ProcessQualityControlService.addQualityStandard().then(res => {
      if (res.data.code != 200) {
        openModalMessage('warning', res.data.msg)
        return
      }
      this.fetch()
    })
  }
  //初始化加载数据
  fetch = (pageNum = 1, pageSize = 100) => {
    this.setState({ loading: true })
    const { searchItem } = this.state
    searchItem.pageNum = pageNum
    searchItem.pageSize = pageSize

    ProcessQualityControlService.findPlanAll(searchItem).then(res => {
      this.setState({ loading: false })
      if (res.data.data.code !== 200) {
        openModalMessage('warning', res.data.data.msg)
        return
      }
      this.setState({ dataSource: res.data.data.data, total: res.data.data.total, pageNum, pageSize })
    }).catch(err => {
      openModalMessage('error', err.message)
    })
  }
  getList = () => {
    // 派工班组查询
    ProductionOrderService.findGroupAll().then(res => {
      if (res.data.code !== 200) {
        openModalMessage('warning', res.data.msg)
        return
      }
      const departmentList = res.data.data
      this.setState({ departmentList });
    }).catch(err => {
      openModalMessage('error', err.message)
    })
    // 工序查询
    APIService.addReturnMessage().then(res => {
      if (res.data.code !== 200) {
        openModalMessage('warning', res.data.msg)
        return
      }
      let procedureData = res.data.data
      this.setState({ procedureData })
    }).catch(err => {
      openModalMessage('error', err.message)
    })
  }

  // 打开详情页
  openDetails = (url, record, value) => {
    if (!url) {
      this.props.history.push({ pathname: "/404" })
    } else {
      const { searchItem, dataSource, modelStandard, imgList } = this.state
      let data = { dataSource, searchItem, imgList, formData: { ...modelStandard, ...record, ...value } }
      localStorage.setItem('ProcessQualityControl_' + url, JSON.stringify(data))
      this.props.history.push({ pathname: "/ProcessQualityControl_" + url, data })
    }
  }

  //详情/编辑
  edit = (record) => {
    ProcessQualityControlService.findPlanDetailsAll(`qualityStandardId=${record.id}&userId=${localStorage.getItem('userId')}`).then(res => {
      if (res.data.code != 200) {
        openModalMessage('warning', res.data.msg)
        return
      }
      let data = res.data.data
      let modelStandard = data.modelStandard
      let dataSource = data.fromVoList
      let imgList = data.imgList
      console.log(dataSource, 'dataSource+++++++++++++++++');
      this.setState({
        data, modelStandard, dataSource, imgList
      }, () => {
        // 跳转到不同的详情页
        if (modelStandard.formName == "机架水平精度调校标准") {
          this.openDetails('Precision', record, data)
        }
        else if (modelStandard.formName == "尾板调节螺母配合精度记录表") {
          this.openDetails('Pygidium', record, data)
        }
        else if (modelStandard.formName == "哥林柱与头板垂直度装配标准") {
          this.openDetails('Cephalic', record, data)
        }
        else if (modelStandard.formName == "三大板下孔等高检测标准") {
          this.openDetails('Bottomhole', record, data)
        }
        else if (modelStandard.formName == "哥林柱与机架导轨面平行度标准") {
          this.openDetails('Parallel', record, data)
        }
        else if (modelStandard.formName == "大机装配检查标准（装配外观）") {
          this.openDetails('Bigexamine', record, data)
        }
        else if (modelStandard.formName == "大机装配检查标准（装配过程）") {
          this.openDetails('BigExamineAssemble', record, data)
        } else {
          this.openDetails()
          // openModalMessage('warning', res.data.msg)
        }
      })
    })
  };

  handleCancel = e => {
    this.formChooseBill && this.formChooseBill.resetFields();
    this.setState({
      selectedRowKeys: [],
      selectedRows: [],
      btnLoading: false,
      visiable_AddForm3: false
    });
    this.fetch();
  };

  // 查询
  handleSearch = () => {
    if (this.state.activeKey == '0') {
      this.formSearch.validateFields((err, value) => {
        if (err) return
        console.log(value)
        this.setState({ searchItem: value }, () => {
          this.init()
        });
      })
    } else if (this.state.activeKey == '1') {
      this.formSelfSearch.validateFields((err, value) => {
        if (err) return
        console.log(value)
        this.setState({ selfSearchItem: value }, () => {
          if (this.SelfCheckingRef) {
            this.SelfCheckingRef.getSearchItem(value)
          }
        });
      })
    }
  };

  onHandleAdvanced = () => {
    this.setState({ advanced: !this.state.advanced })
  }
  loadData = (value, dataSource) => {
    console.log(value, dataSource)
  }
  // 选择某一行数据
  chooseRow = record => {
    let flag = true;
    let index = 0;
    this.state.selectedRowKeys.forEach((row, i) => {
      if (row === record.id) {
        flag = false;
        index = i;
      }
    })
    const selectedRowKeys = this.state.selectedRowKeys;
    const selectedRows = this.state.selectedRows;
    if (flag) {
      selectedRowKeys.push(record.id);
      selectedRows.push(record);
    } else {
      selectedRowKeys.splice(index, 1);
      selectedRows.splice(index, 1);
    }
    this.setState({ selectedRowKeys: selectedRowKeys, selectedRows: selectedRows });
  };

  // 点击结果修正
  chechResult = (record) => {
    const { activeKey } = this.state
    if (activeKey == '0') {
      const { selectedRows } = this.state
      if (!selectedRows || !selectedRows.length) {
        openModalMessage('warning', '请选择要修改的项目！');
        return;
      }
      this.setState({ visiable_AddForm3: true })
    } else if (activeKey == '1') {
      if (this.SelfCheckingRef) {
        let { selectedRows, selectedRowKeys } = this.SelfCheckingRef.getSelectedRows()
        if (!selectedRows || !selectedRows.length) {
          openModalMessage('warning', '请选择要修改的项目！');
          return;
        }
        this.setState({ visiable_AddForm3: true, selfSelectedRowKeys: selectedRowKeys })
      }
    }

  }
  // 提交结果修正
  submit_checkResult = () => {
    this.formAdd3.validateFields((err, value) => {
      if (err) return;
      this.save(value)
    })
  }
  // 变更/批量修改
  save = (data) => {
    this.setState({ btnLoading: true })
    let obj = {
      "checkResult": data.checkResult,
      "userId": localStorage.getItem('userId'),
    }

    console.log(obj, '变更/批量修改');
    // 过程记录表 修改结果
    if (this.state.activeKey == '0') {
      const { selectedRowKeys } = this.state
      obj = {
        ...obj,
        "id": selectedRowKeys,
      }

      ProcessQualityControlService.updateCheckResult(obj).then(res => {
        console.log(res)
        this.setState({ btnLoading: false })
        if (res.data.code !== 200) {
          openModalMessage('warning', res.data.msg);
          return;
        }
        openSuccessModal(res.data.msg);
        this.handleSearch()
        this.handleCancel()
      }).catch(err => {
        openModalMessage('error', err.message);
      })
    }
    // 自检表单 修改结果
    else if (this.state.activeKey == '1') {
      const { selfSelectedRowKeys } = this.state
      obj = {
        ...obj,
        "testCheckId": selfSelectedRowKeys,
      }
      ProcessQualityControlService.updateFromCheckResult(obj).then(res => {
        console.log(res)
        this.setState({ btnLoading: false })
        if (res.data.code !== 200) {
          openModalMessage('warning', res.data.msg);
          return;
        }
        openSuccessModal(res.data.msg);
        this.handleSearch()
        this.handleCancel()
      }).catch(err => {
        openModalMessage('error', err.message);
      })
    }
  }
  // 导出
  downloadFather = () => {
    const { selectedRows } = this.state;

  }
  // 跨页全选
  fetchAll = async () => {
    const { searchItem, total } = this.state
    searchItem.pageNum = 1
    searchItem.pageSize = total
    await ProcessQualityControlService.findPlanAll(searchItem).then(res => {
      if (res.data.data.code !== 200) {
        openModalMessage('warning', res.data.data.msg)
        return
      }
      const dataSourceAll = res.data.data.data
      const selectedRowKeys = dataSourceAll.map(item => item.batchNo);
      this.setState({ dataSourceAll, selectedRowKeys, selectedRows: dataSourceAll })
    }).catch(err => {
      openModalMessage('error', err.message)
    })
  }

  onChangeTabs = activeKey => {
    this.setState({ activeKey }, this.handleSearch);
  };
  // 重置
  resetForm = () => {
    this.formSearch && this.formSearch.resetFields();
    this.formSelfSearch && this.formformSelfSearchSearch.resetFields();
    this.setState({
      searchItem: {
        department: localStorage.getItem('workShop')
      }
    }, this.init);
  }

  render() {
    const { visiable_AddForm3, departmentList, procedureData, loading, dataSource, advanced, columns, pageNum, pageSize, total, selectedRowKeys, downloadLoading, searchItem, selfSearchItem, btnLoading } = this.state;
    const rowSelection = {
      type: 'checkbox',
      selectedRowKeys: selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          selectedRows: selectedRows,
          selectedRowKeys: selectedRowKeys,
        })
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        const keys = [... this.state.selectedRowKeys];
        const rows = [... this.state.selectedRows];
        if (selected) {
          changeRows.forEach(row => {
            if (isInvalidObject(keys.find(key => key === row.id))) {
              keys.push(row.id);
              rows.push(row);
            }
          })
        } else {
          changeRows.forEach(row => {
            keys.splice(keys.indexOf(row.id), 1);
            rows.splice(rows.indexOf(row), 1);
          })
        }
        this.setState({ selectedRows: rows, selectedRowKeys: keys })
      }
    }
    return (
      <div>
        <BasicLayoutSearch>
          <PageHeader
            style={{ padding: '4px 24px' }}
            title={`过程质量管控`}>
          </PageHeader>
          <Divider />
          {
            this.state.activeKey == '0' ?
              <SearchForm onSearch={this.handleSearch}
                onClick={this.onHandleAdvanced}
                advanced={advanced}
                searchItem={searchItem}
                departmentList={departmentList}
                resetForm={this.resetForm}
                ref={node => (this.formSearch = node)}
              /> :
              this.state.activeKey == '1' ?
                <SelfCheckingSearchForm onSearch={this.handleSearch}
                  onClick={this.onHandleAdvanced}
                  advanced={advanced}
                  searchItem={selfSearchItem}
                  procedureData={procedureData}
                  resetForm={this.resetForm}
                  ref={node => (this.formSelfSearch = node)}
                /> :
                null
          }
        </BasicLayoutSearch>
        <Tabs tabBarExtraContent={(
          <div className='mydiv'>
            {[
              <XZButton key='1' onClick={() => this.chechResult()} icon="edit" />,
              <DownLoadButton key='2' onClick={() => { this.downloadFather() }} icon="download" loading={downloadLoading} />
              // <Button key={1} type="primary" onClick={() => this.chechResult()} icon="edit">修改结果</Button>,
              // <Button type="primary" key={2} onClick={() => { this.downloadFather() }} icon="download" loading={downloadLoading}>导出</Button>,
            ]}
          </div>
        )}
          hideAdd
          className="layout-model"
          onChange={this.onChangeTabs}
          activeKey={this.state.activeKey}
          type="card">
          <TabPane tab={'过程记录表'} key="0" closable={false}>
            <Alert message={<div>已选择<span style={{ color: '#fd1818', margin: '0 3px' }}>{selectedRowKeys.length}</span>项</div>} type="info" showIcon style={{ marginBottom: 15 }} />
            <TableCustomize
              columns={columns}
              rowKey={(record) => record.id}
              dataSource={dataSource}
              pagination={false}
              loading={loading}
              allowDrafting={true}
              allowRowEdit={true}
              rowSelection={rowSelection}
              onRow={(record, rowKey) => ({
                onClick: this.chooseRow.bind(this, record, rowKey)
              })}
              allowEditable={this.loadData}
              scroll={{ x: true, y: 600 }}
              rowClassName={(record, index) => {
                return (['editable-row', index % 2 === 0 ? 'editable-row' : 'editable-row12'])
              }}
            />
            <BasicPagination pageNum={pageNum} pageSize={pageSize} total={total} loadData={this.fetch} />
          </TabPane>
          <TabPane tab={'自检表单'} key="1" closable={false}>
            <SelfChecking
              onRef={(ref) => this.SelfCheckingRef = ref}
              searchItem={searchItem}
            />
          </TabPane>
        </Tabs>

        {/* 批量修改检验结果 */}
        <Modal
          visible={visiable_AddForm3}
          destroyOnClose
          title={'批量修改结果'}
          onOk={this.submit_checkResult}
          onCancel={this.handleCancel}
          okText="确定"
          cancelText="取消"
          maskClosable={false}
          confirmLoading={btnLoading}
        >
          <AddForm3
            ref={node => (this.formAdd3 = node)}
          />
        </Modal>
      </div>
    );
  }
}
export default Form.create()(withRouter(ProcessQualityControl));
